package xyz.naokeziteng.data_structure.graph_theory;

import java.util.Arrays;

/**
 * @author hawk
 * @date 2022/10/8
 * @desc 单源路径
 **/
public class DfsSingleSourcePath {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    //源头
    private int s;

    /**
     * @param G 图
     * @param s 源
     */
    public DfsSingleSourcePath(Graph G, int s) {
        G.validateVertex(s);
        this.s = s;
        this.G = G;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);
        dfs(s, s);
    }

    //深度优先遍历
    private void dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                dfs(w, v);
            }
        }
    }

    public boolean isConnected(int t) {
        G.validateVertex(t);
        return visited[t];
    }

    //寻找单源路径
    public String path(int v) {
        G.validateVertex(v);
        if (!isConnected(v)) {
            return "没有路径...";
        }
        StringBuilder sb = new StringBuilder();
        int p = v;
        while (p != s) {
            sb.append(p).append("<--");
            p = pre[p];
        }
        return sb.append(p).toString();
    }


    public static void main(String[] args) {
        DfsSingleSourcePath adj = new DfsSingleSourcePath(new Graph("src/main/resources/g.txt"), 0);
        System.out.println(Arrays.toString(adj.pre));
        System.out.println(adj.path(6));
        System.out.println(adj.path(5));
        System.out.println(adj.path(0));
        System.out.println(adj.path(1));
    }
}
